package com.ido.feishu;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;

import javax.annotation.PostConstruct;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * 飞书客户端
 * Create by zoub
 * Date 2025/4/23 10:55 AM
 */
@Slf4j
@Component
public class FeiShuClient {

    private static FeiShuConfig config;


    @Autowired
    private FeiShuConfig feiShuConfig;

    @PostConstruct
    private void init() {
        config = feiShuConfig;
    }


    /**
     * 发送机器人消息
     *
     * @param message
     */
    public void sendMsg(FeiShuMessage message) {
        send(message);
    }


    public static Boolean send(FeiShuMessage message) {
        try {
            // 获取sign
            int timestamp = (int) (System.currentTimeMillis() / 1000);
            String sign = getSign(config.getSecret(), timestamp);
            message.setTimestamp(String.valueOf(timestamp));
            message.setSign(sign);

            ObjectMapper objectMapper = new ObjectMapper();
            String body = objectMapper.writeValueAsString(message);
            log.info("【飞书】发送消息：{}", message);
            String result = HttpUtil.post(config.getWebhook(), body);
            log.info("【飞书】发送结果: {}", result);
            JSONObject res = JSONObject.parseObject(result);
            // 发送成功返回code = 0
            return res.getIntValue("code") == 0;
        } catch (Exception e) {
            log.info("【飞书】发送机器人消息异常：{}", e.getMessage());
        }
        return false;
    }


    /**
     * 得到加密签名
     *
     * @param secret
     * @param timestamp
     * @return
     */
    private static String getSign(String secret, int timestamp) {
        //把timestamp+"\n"+密钥当做签名字符串
        String stringToSign = timestamp + "\n" + secret;
        //使用HmacSHA256算法计算签名
        Mac mac = null;
        try {
            mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(stringToSign.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }
        byte[] signData = mac.doFinal(new byte[]{});
        return new String(Base64Utils.encode(signData));
    }


}
